const { exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
const rmdir = require("../../lib/rmdir");
const readSetting = require("../../lib/read_setting");
const CMD = require("../../lib/break_video");

module.exports = (req, res) => {

    let { findPath, newname, outputPath, oldname, breakImage = false, breakMp3 = false, imageSize, rate = 1, currentIndex } = req.body;

    if (!newname.trim()) return res.send({ code: 400, msg: "未填写文件名称", result: '', ...req.body });

    if (!oldname.trim()) return res.send({ code: 400, msg: "数据被恶意纂改", result: '', ...req.body });

    outputPath = outputPath || readSetting().output_path || path.join(os.homedir(), 'Desktop');

    if (!findPath.trim()) return res.send({ code: 400, msg: "检索路径不存在", result: '', ...req.body });

    if (!/^(true|false)$/.test(breakImage)) return res.send({ code: 400, msg: "分解为图片配置不合法", result: '', ...req.body });

    if (!/^(true|false)$/.test(breakMp3)) return res.send({ code: 400, msg: "分解为MP3设置不合法", result: '', ...req.body });

    if (/^false$/.test(breakImage) && /^false$/.test(breakMp3)) return res.send({ code: 400, msg: "什么都不选，你想干嘛？", result: '', ...req.body });

    if (imageSize && /^(true|false)$/.test(breakImage)) {
        if (/^\d+\*\d+$/.test(imageSize)) {
            imageSize = imageSize.replace("*", 'x');
        } else {
            return res.send({ code: 400, msg: "图片大小的格式设置不合法", result: '', ...req.body });
        }
    } else {
        imageSize = false;
    }

    rate = rate * 1;

    if (breakImage && (!/^\d+$/.test(rate) || rate < 1)) return res.send({ code: 400, msg: "截图频率不合法", result: '', ...req.body });

    if (!fs.existsSync(outputPath)) {
        try {
            fs.mkdirSync(outputPath, { recursive: true });
        } catch (error) {
            return res.send({ code: 400, msg: "输出路径错误！", result: '', ...req.body });
        }
    }

    let filepath = path.join(findPath, oldname);

    new Promise(async (resolve, reject) => {

        let savePath = path.resolve(outputPath, newname);

        if (fs.existsSync(savePath)) {
            // return reject("目标目录下存在同名文件！！！")
            await rmdir(savePath);
        };

        let cmds = CMD(filepath, savePath, newname, breakImage, breakMp3, imageSize, rate);


        if (cmds.length === 1) {
            exec(cmds[0], (err, stdout, stderr) => {
                if (err) return reject(err);
                resolve({ savePath, newname });
            })
        } else if (cmds.length === 2) {

            new Promise((r, j) => {
                exec(cmds[0], (err, stdout, stderr) => {
                    if (err) return j(err);
                    r();
                })
            }).then(() => {
                exec(cmds[1], (err, stdout, stderr) => {
                    if (err) return reject(err);
                    resolve({ savePath, newname });
                })
            }).catch(err => {
                reject(err);
            })
        }

    }).then(({ savePath, newname }) => {
        exec(`explorer "${outputPath}"`, (err, stdout, stderr) => {
            if (err) console.log(err);
        })
        res.send({
            code: 200,
            state: true,
            filename: newname,
            currentIndex,
            result: savePath,
            msg: `${newname} 分解成功！`
        })
    }).catch(err => {
        console.log(err);
        let errObj = {
            code: 500,
            state: false,
            filename: newname,
            currentIndex,
            result: err,
            msg: `${newname} 分解失败！`
        };
        res.send(errObj);
    })
}